# -- coding: utf-8 --
# Name: app

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import config

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)


class Writer(db.Model):
    __tablename__ = 'writer'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    books = db.relationship('Book', backref='writers')


class Book(db.Model):
    __tablename__ = 'books'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50), nullable=False)
    publishing_office = db.Column(db.String(50), nullable=False)
    isbn = db.Column(db.String(50), nullable=False)
    writer_id = db.Column(db.Integer, db.ForeignKey('writer.id'))


db.create_all()


@app.route('/add')
def add():
    user1 = Writer(name='lixianghua')
    user2 = Writer(name='Sweigart')
    db.session.add(user1)
    db.session.add(user2)
    book1 = Book(title='java how to use', publishing_office='thsinghua', isbn='213123123123', writer_id='1')
    book2 = Book(title='python how to use', publishing_office='thsinghua', isbn='123456789', writer_id='1')
    book3 = Book(title='golang how to use', publishing_office='jixie', isbn='789456123', writer_id='2')
    db.session.add(book1)
    db.session.add(book2)
    db.session.add(book3)
    return 'add data success'


@app.route('/select')
def select():
    writer = Writer.query.filter(Writer.id == '1').first()
    book = Writer.books
    for k in book:
        print(k)
    book = Book.query.filter(Book.id == '1').first()
    writer = Book.writers
    print(writer.name)
    return "selected success"


@app.route('/')
def hello_world():
    return 'hello world'


if __name__ == '__main__':
    app.run()





